//
//  AccountSingleton+Widget.m
//  HomeMate
//
//  Created by Air on 17/2/24.
//  Copyright © 2017年 Air. All rights reserved.
//

#import "AccountSingleton+Widget.h"

static NSString *const WidgetCurrentUserInfoKey = @"widgetCurrentUserInfo";

@implementation AccountSingleton (Widget)

-(void)widgetLoginWithUserName:(NSString *)userName password:(NSString *)password completion:(commonBlock)completion
{
    DLog(@"当前登录账号：%@ 密码：%@",userName,password);
    
    __weak typeof(self)weakSelf = self;

    self.currentPassword = password;
    self.currentUserName = userName;
    
    NSDictionary *userInfoDic = [self.widgetUserDefault objectForKey:WidgetCurrentUserInfoKey];    // 主 App 登录的用户的信息
    NSString *lastFamilyId = userInfoDic[@"familyId"];
    
    LoginCmd *cmd = [HMLoginAPI cmdWithUserName:userName password:password];
    sendCmd(cmd, ^(KReturnValue returnValue, NSDictionary *returnDic) {
        
        if (returnValue == KReturnValueSuccess) {
            
            DLog(@"登录成功");
            
            weakSelf.userId = returnDic[@"userId"];
            weakSelf.familyId = lastFamilyId;
            
            // 登录成功，把当前登录的账号，密码信息保存下来
            [weakSelf widget_addLocalAccountWithUserName:userName password:password userId:weakSelf.userId familyId:lastFamilyId];
        }
        
        if (completion) {
            completion(returnValue);
        }
    });
}

-(void)widget_addLocalAccountWithUserName:(NSString *)userName password:(NSString *)password
                                   userId:(NSString *)userId familyId:(NSString *)familyId
{
    DLog(@"当前账号信息：userName = %@ userId = %@ familyId = %@",userName,userId,familyId);
    
    HMLocalAccount *account = [[HMLocalAccount alloc] init];
    account.password = password;
    account.lastUserName = userName;
    account.loginTime = [[NSDate date] timeIntervalSince1970];
    account.userId = userId;
    [account insertObject];

    [self saveCurrentLocalAccount:account];
    
    if (userName && password && userId) {
        
        // 保存当前用户信息到公用的 widget 
        NSDictionary *dic = @{@"userName"  : userName
                            , @"password"  : password
                            , @"userId"    : userId};
        
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:dic];
        
        if (familyId) {
            [userInfo setObject:familyId forKey:@"familyId"];
        }
        
        [self.widgetUserDefault setObject:userInfo forKey:WidgetCurrentUserInfoKey];
        [self.widgetUserDefault synchronize];
    }
}


@end
